 <template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="11" :lg="11" :xl="11" style="margin-bottom: 10px">
        <el-card class="box-card">  
          <div class="head-container">
              <el-form ref="form" :model="form" size="small" label-width="80px">
                <el-input v-model="form.id"  style="width: 370px;display:none;" />

                <div style="text-align: center" class="site-head">
                  <div class="el-upload">
                    <img :src="baseApi + 'files/' + form.imgfile" title="点击上传头像" class="avatar" @click="toggleShowUpload">
                    <myUpload
                      v-model="showUpload"
                      :headers="headers"
                      :params="uploadParam"
                      :url="uploadUrl"
                      @crop-upload-success="cropUploadSuccess"
                    />
                  </div>
                </div>

                <el-form-item label="名称">
                  <el-input v-model="form.sitename" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="编码">
                  <el-input v-model="form.sitecode" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="位置">
                  <el-input v-model="form.position" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="负责人">
                  <el-input v-model="form.manager" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="form.phone" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="form.email" style="width: 370px;" />
                </el-form-item>
                <el-form-item label="排序">
                  <el-input v-model="form.sortName" style="width: 370px;" />
                </el-form-item>
              </el-form>


              <div slot="footer" class="dialog-footer">
                <el-button :loading="crud.cu === 2" type="primary" @click="submit">保存</el-button>
                <el-button :loading="crud.cu === 2" type="primary" @click="closeBack()">返回</el-button>
              </div>
          </div>  
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="13" :lg="13" :xl="13" v-show="form.id">
        <el-card class="box-card">
          <div class="clearfix">
            <span>场地添加完成即可在场地中 <el-button @click="toEquips()" type="primary" plain>维护设备</el-button></span>
          </div>
        </el-card> 
        <div></div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>权限详情</span>
            <el-button
              v-if="checkPermission(['admin','']) && this.$refs.siteAcl"
              class="filter-item"
              size="mini"
              style="float: right;padding: 4px 10px"
              type="primary"
              icon="el-icon-plus"
              @click="$refs.siteAcl && $refs.siteAcl.openSelectUser()"
            >新增</el-button>
          </div>
          <siteAcl ref="siteAcl" :sid="form.id" :permission="permission" />          

        </el-card>
      </el-col>      
    </el-row>
  </div>  
</template>


<script>
import myUpload from 'vue-image-crop-upload'
import checkPermission from '@/utils/permission'
import crudIotSite from '@/api/iot/iotSite'
import siteAcl from './siteAcl'
import { mapGetters } from 'vuex'
import store from '@/store'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import customOperation from "@crud/customOperation";

const defaultForm = { id: null, sitename: null, sitecode: null, imgfile: null, position: null, manager: null, phone: null, email: null, sort: null, createtime: null, updatetime: null }
export default {
  name: 'siteAdd',
  components: { crudOperation, rrOperation, udOperation, customOperation, siteAcl, myUpload },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '场地', sort: 'id,desc', crudMethod: { ...crudIotSite }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'iotSite:add'],
        edit: ['admin', 'iotSite:edit'],
        del: ['admin', 'iotSite:del']
      },
      headers: {
        'Authorization': getToken()
      },
      showUpload: false,
      uploadUrl: '/files',
      uploadParam: {
        dataId: this.$route.query._PK_
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },  
  created() {
  },
  mounted: function() {
    const query = this.$route.query
    if (query._PK_) { // 后端获取数据
      this.edit = true
      this.form.id = Number(query._PK_)
      crudIotSite.getById(query._PK_).then(res => {
        Object.assign(this.form, res)
      })
      this.showAclList(query._PK_)
    }
  },
  methods: {
    checkPermission,
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return false
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = 2
        this.edit ? this.customEdit() : this.customAdd()
      })
    },
    showAclList(siteId) {
      if (this.$refs.siteAcl) {
        this.$refs.siteAcl.query.siteid = siteId
        this.$refs.siteAcl.siteid = siteId
        this.$refs.siteAcl.crud.toQuery()        
      }
    },
    /**
     * 执行自定义添加
     */
    customAdd() {
      this.crud.crudMethod
        .add(this.form)
        .then((res = {}) => {
          this.loading = 0
          if (res.RTN_CODE && res.RTN_CODE === 'ERROR') {
            this.crud.notify(res.MSG, CRUD.NOTIFICATION_TYPE.ERROR)
          } else {
            this.edit = true
            this.crud.addSuccessNotify()
            this.form.id = res.id
            this.showAclList(res.id)
          }
        })
        .catch(e => {
          this.loading = 0
          console.error(e)
        })
    },
    /**
     * 执行自定义编辑
     */
    customEdit() {
      this.crud.crudMethod
        .edit(this.form)
        .then(() => {
          this.loading = 0
          this.crud.editSuccessNotify()
        })
        .catch(e => {
          this.loading = 0
          console.error(e)
        })
    },
    closeBack() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },
    cropUploadSuccess(jsonData, field) {
      this.form.imgfile = jsonData.id
    },
    toggleShowUpload() {
      this.showUpload = !this.showUpload
    }, 
    toEquips() {
      const query = {}
      query.siteid = this.form.id    
      //this.$router.options.routes  
      // this.$router.matcher 中查看 addRoutes
      debugger
      this.$router.push({
        path: "/iot/IotEquip",
        query
      })
    }    
  }
}
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.site-head .avatar {
  width: 200px;
  padding-bottom: 5px;
}
</style>